//
//  ViewController.m
//  BackgroundPlayAudio
//
//  Created by 大宝 刘 on 11-12-7.
//  Copyright (c) 2011年 北京帷幄昊合数字娱乐科技有限公司. All rights reserved.
//

#import "ViewController.h"

@implementation ViewController
@synthesize audioPlayer = _audioPlayer;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (IBAction)playButton:(id)sender {
    [self playAudio:@"白龙马"];
}

-(void)playAudio:(NSString *) fileName {
    
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"mp3"];        
    NSURL *url = [[NSURL alloc] initFileURLWithPath:soundPath];
    
    AVAudioPlayer *ap = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive: YES error: nil];
    ap.delegate = self;
    
    self.audioPlayer = ap;
    
    if (self.audioPlayer == nil)
        NSLog(@"错误");
    else{
        UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;
        
        [self.audioPlayer prepareToPlay];
        
        if([self.audioPlayer play]){
            
            newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
            
        }
        
        if (newTaskId != UIBackgroundTaskInvalid && bgTaskId != UIBackgroundTaskInvalid)
            [[UIApplication sharedApplication] endBackgroundTask: bgTaskId];
        
        bgTaskId = newTaskId;
    }
    
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    NSLog(@"finished now next...");
}

@end
